<?php


namespace Appstore\Controller;

use Appstore\Model;
use Think\Controller;
use Think\Page;

class IndexController extends BaseController
{

    public function index()
    {

        $data=S('appstore_home');
        if($data===false){


            $data['shop_count']=D('AppstoreShop')->where(array('status'=>1))->count();
            $data['goods_count']=D('AppstoreGoods')->where(array('status'=>1))->count();
            $data['order_count']=D('AppstoreOrder')->where(array('status'=>1))->count();
            $data['download_count']=D('AppstoreVersion')->where(array('status'=>1))->sum('download_count');
            $data['news_top']=D('News')->where(array('category'=>14,'status'=>1,'dead_line'=>array('gt',time())))->order('create_time desc')->limit(1)->select();
            $data['news_top']= $data['news_top'][0];
            $data['news']=D('News')->where(array('category'=>14,'status'=>1,'dead_line'=>array('gt',time())))->order('create_time desc')->limit(1,3)->select();

            $shops=explode(',',modC('RECOMMOND_SHOPS'));
            foreach($shops as &$v){
                $v=D('AppstoreShop')->where(array('status'=>1))->find($v);
            }
            unset($v);
            $data['shops']=$shops;

            $plugins=explode(',',modC('RECOMMOND_PLUGINS'));
            foreach($plugins as &$v){
                $v=D('AppstorePlugin')->getById($v);
            }
            unset($v);
            $data['plugins']=$plugins;
            $data['hot_plugins_free']= D('AppstorePlugin')->getLimit(array('need_buy'=>0,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'watch_count desc',1);
            $data['hot_plugins_pay']= D('AppstorePlugin')->getLimit(array('need_buy'=>1,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'sales desc',1);

            $modules=explode(',',modC('RECOMMOND_MODULES'));
            foreach($modules as &$v){
                $v=D('AppstoreModule')->getById($v);
            }
            unset($v);
            $data['modules']=$modules;
            $data['hot_modules_free']= D('AppstoreModule')->getLimit(array('need_buy'=>0,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'watch_count desc',1);
            $data['hot_modules_pay']= D('AppstoreModule')->getLimit(array('need_buy'=>1,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'sales desc',1);



            $themes=explode(',',modC('RECOMMOND_THEMES'));
            foreach($themes as &$v){
                $v=D('AppstoreTheme')->getById($v);
            }
            unset($v);
            $data['themes']=$themes;
            $data['hot_themes_free']= D('AppstoreTheme')->getLimit(array('need_buy'=>0,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'watch_count desc',1);
            $data['hot_themes_pay']= D('AppstoreTheme')->getLimit(array('need_buy'=>1,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'sales desc',1);

            $themes=explode(',',modC('RECOMMOND_SERVICES'));
            foreach($themes as &$v){
                $v=D('AppstoreService')->getById($v);
            }
            unset($v);
            $data['services']=$themes;
            $data['hot_services_free']= D('AppstoreService')->getLimit(array('need_buy'=>0,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'watch_count desc',1);
            $data['hot_services_pay']= D('AppstoreService')->getLimit(array('need_buy'=>1,'status' => 1,'update_time'=>array('gt',time()-60*60*24*30)), 5, 'sales desc',1);



            S('appstore_home',$data,600);

        }




        $this->assign('tab', 'home');
        $this->assign($data);
        $this->display();
    }

    /**
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function search()
    {
        $aKeywords=I('keywords','','text');
        $param = I('get.', 'text');
        $param['keywords']=$aKeywords;
        $map['status'] = 1;
        if(!($param['entity']>0)){
            $param['entity']=0;
        }else{
            $map['entity']=$param['entity'];
        }

        list($order, $param, $map) = $this->handleParam($param, $map);
        $map = $this->handleKeywords($aKeywords, $map);
        $data = D('AppstoreGoods')->getListPage($map, 10, $order, 1);
        $this->assign('lists', $data);
        $this->display();
    }

    /**
     * 处理ajax订阅事件
     */
    public function watch()
    {
        if (!is_login()) {
            $this->error('请登录后再订阅。');
        }
        $aId = I('post.goods_id', 0, 'intval');
        if ($aId) {
            $watchModel = D('AppstoreWatch');
            $rs = $watchModel->watch($aId);
            if ($rs === false) {
                $this->error('订阅失败。' . $watchModel->getError());
            } else {
                $this->success($rs);
            }

        } else {
            $this->error('订阅失败，参数错误。');
        }


    }

    public function feed()
    {
        $aPage = I('get.page', '1', 'intval');
        $versionModel = D('AppstoreVersion');
        $dbPrefix = C('DB_PREFIX');
        $versionCount = $versionModel->query("select count({$dbPrefix}appstore_version.id) as total from {$dbPrefix}appstore_version,{$dbPrefix}appstore_goods where {$dbPrefix}appstore_version.goods_id= {$dbPrefix}appstore_goods.id and {$dbPrefix}appstore_goods.status=1  and {$dbPrefix}appstore_version.status=1 ");
        $versions['html'] = getPagination($versionCount[0]['total'], 10);

        $form = ($aPage - 1) * 10;
        $to = $form + 10;
        $versions['data'] = $versionModel->query(<<<str
        select {$dbPrefix}appstore_version.id,{$dbPrefix}appstore_version.title,{$dbPrefix}appstore_version.goods_id,{$dbPrefix}appstore_version.create_time,{$dbPrefix}appstore_version.log  from {$dbPrefix}appstore_version,{$dbPrefix}appstore_goods where {$dbPrefix}appstore_version.goods_id= {$dbPrefix}appstore_goods.id and {$dbPrefix}appstore_goods.status=1
         and {$dbPrefix}appstore_version.status=1  order by {$dbPrefix}appstore_version.create_time desc limit {$form},{$to}
str
        );

        //   $versionModel->order('create_time desc')->where('status=1')->findPage(10);
        $goodsModel = D('AppstoreGoods');
        foreach ($versions['data'] as $key => $v) {
            $versions['data'][$key]['goods'] = $goodsModel->find($v['goods_id']);
            if (!$versions['data'][$key]['goods']) {
                unset($versions['data'][$key]);
            }
            $versions['data'][$key]['user'] = query_user(array('space_link'), $versions['data'][$key]['goods']['uid']);
            $versions['data'][$key]['log'] = $versionModel->formatLog($v['log']);
        }
        $this->assign('versions', $versions);
        $this->assign('current', 'feed');
        $this->display();
    }

    private function checkIsLast($version_id)
    {
        $goods = get_goods_by_versionid($version_id);
        $last = get_last_version($goods['id']);
        if ($last['id'] != $version_id) {
            $this->error('参数错误');
        }
    }

    public function buy()
    {
        if (!is_login()) {
            $this->error('少年，你得先登录啊。');
        }

        if (IS_POST) {
            $aVersionId = I('post.version_id', 0, 'intval');
            $aPriceId = I('post.price_id', 0, 'intval');
            $aModel = I('post.model', 'price', 'text');
            $this->checkIsLast($aVersionId);
            $version = D('AppstoreVersion')->getVersion($aVersionId);
            if ($aModel == 'price') {
                $priceModel = D('AppstorePrice');
                $price = $priceModel->getById($aPriceId);
                if ($price['version_id'] != $aVersionId) {
                    $this->error('参数错误。');
                }
                $finally = get_finally_price($aPriceId);
            } else {
                $history = D('AppstorePriceMax')->where(array('id' => $aPriceId))->find();
                $price = D('AppstorePrice')->where(array('pid' => 0, 'value' => $history['score_id'], 'version_id' => $aVersionId))->find();
                $finally['score'] = $history['score_id'];

                $finally['payment_price'] = ($price['price'] - $history['max_price']) > 0 ? ($price['price'] - $history['max']) : 0;
                $finally['version_price'] = $price['price'];
            }

            $order = D('AppstoreOrder')->where(array('uid' => get_uid(), 'version_id' => $aVersionId, 'status' => 1))->find();
            if ($order) {
                $this->error('请勿重复创建同个版本的订单，如需创建请取消原订单');
            }

            $data['version_id'] = $aVersionId;
            $data['goods_id'] = $version['goods_id'];
            $data['uid'] = get_uid();
            $data['score'] = $finally['score'];
            $data['payment_price'] = $finally['payment_price'];
            $data['version_price'] = $finally['version_price'];
            $res = D('AppstoreOrder')->createOrder($data);
            if ($res) {
                $goods = M('AppstoreGoods')->find($version['goods_id']);
                D('Common/Message')->sendMessage($goods['uid'], query_user('nickname') . '下了订单', '订单要购买的商品——' . text($goods['title']), 'appstore/admin/myplugin', array(), get_uid(), 2);
                $this->redirect('order', array('id' => $res));

            } else {
                $this->error('创建订单失败。');
            }
        } else {
            $aVersionId = I('get.id', '', 'text');

            $this->checkIsLast($aVersionId);
            $version = D('AppstoreVersion')->getVersion($aVersionId);
            $goods = D('AppstoreGoods')->getById($version['goods_id']);
            $price = D('AppstorePrice')->getPriceFilter($aVersionId);

            $score = array();
            $json_price = array();
            foreach ($price as $key => &$val) {
                if ($val['pid'] == 0) {
                    $score = D('Ucenter/Score')->getType(array('id' => $val['value']));
                    $val['text'] = $score['title'] . $val['price'] . $score['unit'];
                    $json_price[$val['model']][$val['id']] = $score['title'] . $val['price'] . $score['unit'];
                    $oPrice = $val['price'];
                } else {
                    if ($val['model'] == 'price') {
                        $role = D('Admin/Role')->getByMap(array('id' => $val['value']));
                        if ($val['price_type'] == 'price') {
                            $p = $score['title'] . $val['price'] . $score['unit'];
                            $json_price[$val['model']][$val['id']] = $score['title'] . $val['price'] . $score['unit'];
                        } else {
                            $p = $score['title'] . $val['price'] . '%';
                            $json_price[$val['model']][$val['id']] = $score['title'] . $val['price'] * $oPrice / 100 . $score['unit'];
                        }
                        $val['text'] = '优惠： ' . $role['title'] . '可享受<span class="re_price">' . $p . '</span>优惠';
                    } else {

                        $val['differ'] = 0;   //todo 暂时已购买用户免费升级。 2015/10/20 駿濤
                        if ($val['differ'] > 0) {
                            $val['text'] = '已购买用户通过补差价：<span class="re_price">' . $score['title'] . $val['differ'] . $score['unit'] . '</span>升级';
                            $json_price[$val['model']][$val['id']] = $score['title'] . $val['differ'] . $score['unit'];
                        } else {
                            $val['text'] = '已购买用户<span class="re_price">免费</span>升级';
                            $json_price[$val['model']][$val['id']] = $score['title'] . 0 . $score['unit'];
                        }

                    }
                }
            }
            unset($val);


            $this->assign('my_score', D('Ucenter/Score')->getAllScore(is_login()));

            $this->assign('json_price', json_encode($json_price));
            $this->assign('price', $price);
            $this->assign('goods', $goods);
            $this->assign('version', $version);
            $this->display();

        }

    }

    public function plugin($keywords = '', $tid = 0)
    {
        $keywords = text($keywords);
        $param = I('get.', 'text');
        $tid = I('tid', 0, 'intval');
        if ($tid != 0) {
            $map['type_id'] = $tid;
        }
        $map['status'] = 1;
        list($order, $param, $map) = $this->handleParam($param, $map);

        $map = $this->handleKeywords($keywords, $map);
        $data = D('AppstorePlugin')->getList($map, 10, $order, 1);
        $this->assign('lists', $data);
        $all = array(array('id' => 0, 'title' => '全部', 'count' => D('AppstoreGoods')->where(array('entity' => 1, 'status' => 1))->count()));
        $types = D('AppstoreType')->where(array('entity' => 1, 'status' => 1))->order('sort desc')->select();

        foreach ($types as &$v) {
            $v['count'] = D('AppstoreGoods')->where(array('entity' => 1, 'type_id' => $v['id'], 'status' => 1))->count();
        }
        unset($v);
        $types = array_merge($all, $types);

        $this->assign('types', $types);
        $this->assign('current_type', $tid);
        $this->assign('current', 'plugin');
        //推荐start
        $can_manage=check_auth('Appstore/Admin/manage', -1);
        $recommend_plugin_ids=modC('recommend_plugin','','Appstore');
        if($recommend_plugin_ids!=''){
            $order="find_in_set(id,'".$recommend_plugin_ids."')";
            $recommond_goods = D('AppstoreGoods')->getLimit(array('entity' => 1, 'status' => 1,'id' => array('in',explode(',',$recommend_plugin_ids))),999,$order);
        }else{
            $recommond_goods=null;

        }
        if($can_manage){
            if($recommend_plugin_ids!=''){
                $goods = D('AppstoreGoods')->where(array('entity' => 1, 'status' => 1, 'id' => array('not in', explode(',',$recommend_plugin_ids))))->select();
            }else{
                $goods = D('AppstoreGoods')->where(array('entity' => 1, 'status' => 1))->select();
            }
            $this->assign('goods', $goods);
        }
        $this->assign('recommond_goods', $recommond_goods);
        $this->assign('can_manage',$can_manage );
        //推荐end
        $this->display('plugin');
    }

    public function module($keywords = '')
    {
        $keywords = op_t($keywords);
        $param = I('get.', 'text');
        $tid = I('tid', 0, 'intval');
        if ($tid != 0) {
            $map['type_id'] = $tid;
        }
        $map['status'] = 1;

        list($order, $param, $map) = $this->handleParam($param, $map);

        $map = $this->handleKeywords($keywords, $map);
        $data = D('AppstoreModule')->getList($map, 10, $order, 1);
        $this->assign('lists', $data);
        $all = array(array('id' => 0, 'title' => '全部', 'count' => D('AppstoreGoods')->where(array('entity' => 2, 'status' => 1))->count()));
        $types = D('AppstoreType')->where(array('entity' => 2, 'status' => 1))->order('sort desc')->select();

        foreach ($types as &$v) {
            $v['count'] = D('AppstoreGoods')->where(array('entity' => 2, 'type_id' => $v['id'], 'status' => 1))->count();
        }
        unset($v);
        $types = array_merge($all, $types);

        //推荐start
        $can_manage=check_auth('Appstore/Admin/manage', -1);
        $recommend_module_ids=modC('recommend_module','','Appstore');
        if($recommend_module_ids!=''){
            $order="find_in_set(id,'".$recommend_module_ids."')";
            $recommond_goods = D('AppstoreGoods')->getLimit(array('entity' => 2, 'status' => 1,'id' => array('in',explode(',',$recommend_module_ids))),999,$order);
        }else{
            $recommond_goods=null;
        }
        if($can_manage){
            if($recommend_module_ids!=''){
                $goods = D('AppstoreGoods')->where(array('entity' => 2, 'status' => 1, 'id' => array('not in', explode(',',$recommend_module_ids))))->select();
            }else{
                $goods = D('AppstoreGoods')->where(array('entity' => 2, 'status' => 1))->select();
            }
            $this->assign('goods', $goods);
        }
        $this->assign('recommond_goods', $recommond_goods);
        $this->assign('can_manage', $can_manage);
        //推荐end

        $this->assign('types', $types);
        $this->assign('current_type', $tid);
        $this->assign('current', 'module');
        $this->display('module');
    }

    public function theme($keywords = '')
    {
        $keywords = text($keywords);
        $tid = I('tid', 0, 'intval');
        $param = I('get.', 'text');
        if ($tid != 0) {
            $map['type_id'] = $tid;
        }
        $map['status'] = 1;
        list($order, $param, $map) = $this->handleParam($param, $map);

        $map = $this->handleKeywords($keywords, $map);
        $data = D('AppstoreTheme')->getList($map, 10, $order, 1);
        $this->assign('themes', $data);
        $all = array(array('id' => 0, 'title' => '全部', 'count' => D('AppstoreGoods')->where(array('entity' => 3, 'status' => 1))->count()));
        $types = D('AppstoreType')->where(array('entity' => 3, 'status' => 1))->order('sort desc')->select();

        foreach ($types as &$v) {
            $v['count'] = D('AppstoreGoods')->where(array('entity' => 3, 'type_id' => $v['id'], 'status' => 1))->count();
        }
        unset($v);
        $types = array_merge($all, $types);

        //推荐start
        $can_manage=check_auth('Appstore/Admin/manage', -1);
        $recommend_theme_ids=modC('recommend_theme','','Appstore');
        if($recommend_theme_ids!=''){
            $order="find_in_set(id,'".$recommend_theme_ids."')";
            $recommond_goods = D('AppstoreGoods')->getLimit(array('entity' => 3, 'status' => 1,'id' => array('in',explode(',',$recommend_theme_ids))),999,$order);
        }else{
            $recommond_goods=null;
        }
        if($can_manage){
            if($recommend_theme_ids!=''){
                $goods = D('AppstoreGoods')->where(array('entity' => 3, 'status' => 1, 'id' => array('not in', explode(',',$recommend_theme_ids))))->select();
            }else{
                $goods = D('AppstoreGoods')->where(array('entity' => 3, 'status' => 1))->select();
            }
            $this->assign('goods', $goods);
        }
        $this->assign('recommond_goods', $recommond_goods);
        $this->assign('can_manage', $can_manage);
        //推荐end

        $this->assign('types', $types);
        $this->assign('current_type', $tid);
        $this->assign('current', 'theme');
        $this->display();
    }

    public function service($keywords = '')
    {
        $keywords = text($keywords);
        $tid = I('tid', 0, 'intval');
        $param = I('get.', 'text');
        if ($tid != 0) {
            $map['type_id'] = $tid;
        }
        $map['status'] = 1;
        list($order, $param, $map) = $this->handleParam($param, $map);

        $map = $this->handleKeywords($keywords, $map);
        $data = D('AppstoreService')->getList($map, 10, $order, 1);
        $this->assign('lists', $data);
        $all = array(array('id' => 0, 'title' => '全部', 'count' => D('AppstoreGoods')->where(array('entity' => 4, 'status' => 1))->count()));
        $types = D('AppstoreType')->where(array('entity' => 4, 'status' => 1))->order('sort desc')->select();

        foreach ($types as &$v) {
            $v['count'] = D('AppstoreGoods')->where(array('entity' => 4, 'type_id' => $v['id'], 'status' => 1))->count();
        }
        unset($v);
        $types = array_merge($all, $types);

        //推荐start
        $can_manage=check_auth('Appstore/Admin/manage', -1);
        $recommend_service_ids=modC('recommend_service','','Appstore');
        if($recommend_service_ids!=''){
            $order="find_in_set(id,'".$recommend_service_ids."')";
            $recommond_goods = D('AppstoreGoods')->getLimit(array('entity' => 4, 'status' => 1,'id' => array('in',explode(',',$recommend_service_ids))),999,$order);
        }else{
            $recommond_goods=null;
        }
        if($can_manage){
            if($recommend_service_ids!=''){
                $goods = D('AppstoreGoods')->where(array('entity' => 4, 'status' => 1, 'id' => array('not in', explode(',',$recommend_service_ids))))->select();
            }else{
                $goods = D('AppstoreGoods')->where(array('entity' => 4, 'status' => 1))->select();
            }
            $this->assign('goods', $goods);
        }
        $this->assign('recommond_goods', $recommond_goods);
        $this->assign('can_manage', $can_manage);
        //推荐end

        $this->assign('types', $types);
        $this->assign('current_type', $tid);
        $this->assign('current', 'service');
        $this->setTitle('服务——云市场');
        $this->display();
    }

    public function goodsdetail()
    {
        $aToken = I('get.token', '', 'text');
        if ($aToken) {
            $token = M('AppstoreToken')->where(array('token' => $aToken))->find();
            if ($token['uid'] != get_uid()) {
                $this->error('此Token不对应当前登录账户，请登录账户之后再访问本页面。');
            }
            $version = D('AppstoreVersion')->getVersionByToken($aToken);
            $goods = $version['goods'];
        } else {
            $aId = I('get.id', 0, 'intval');
            $goods = D('AppstoreGoods')->find(intval($aId));
        }

        switch ($goods['entity']) {
            case 1:
                redirect(U('pluginDetail?id=' . $goods['id']));
                break;
            case 2:
                redirect(U('moduleDetail?id=' . $goods['id']));
                break;
            case 3:
                redirect(U('themeDetail?id=' . $goods['id']));
                break;
            case 4:
                redirect(U('serviceDetail?id=' . $goods['id']));
        }
    }

    public function plugindetail($id = 0)
    {
        $data = D('AppstorePlugin')->getById($id);


        if (!$data) {
            $this->error('404');
        } elseif (     $data['status'] == 2 &&  !check_auth('Appstore/Admin/manage',$data['uid']) ) {
            $this->error('该插件还未审核。');
        } else {
            $versions = $this->getVersions($data);
            $this->assign('versions', $versions);
            $this->assign('data', $data);
            $this->setTitle('{$data.title|text}');
            $this->assign('current', 'plugin');
            $this->display();
        }
    }

    public function servicedetail($id = 0)
    {
        $data = D('AppstoreService')->getById($id);
        if (!$data) {
            $this->error('404');
        } elseif ($data['status'] == 2 && !is_administrator() && $data['uid'] != is_login()) {
            $this->error('该服务还未审核。');
        } else {
            $versions = $this->getVersions($data);
            $this->assign('versions', $versions);
            $this->assign('data', $data);
            $this->setTitle('{$data.title|text}');

            $this->assign('current', 'service');
            $this->display();
        }
    }

    public function moduledetail($id = 0)
    {
        $data = D('AppstoreModule')->getById($id);


        if (!$data) {
            $this->error('404');
        } elseif ($data['status'] == 2 && !is_administrator() && $data['uid'] != is_login()) {
            $this->error('该模块还未审核。');
        } else {
            $versions = $this->getVersions($data);
            $this->assign('versions', $versions);
            $this->assign('data', $data);
            $this->setTitle('{$data.title|text}');
            $this->assign('current', 'module');
            $this->display();
        }
    }

    public function themedetail($id = 0)
    {
        $data = D('AppstoreTheme')->getById($id);


        if (!$data) {
            $this->error('404');
        } elseif ($data['status'] == 2 && !is_administrator() && $data['uid'] != is_login()) {
            $this->error('该主题还未审核。');
        } else {
            $versions = $this->getVersions($data);
            $this->assign('versions', $versions);
            $data['cover'] = explode(',', $data['cover']);
            $this->assign('data', $data);
            $this->setTitle('{$data.title|text}');
            $this->assign('current', 'theme');
            $this->display();
        }
    }


    public function developer()
    {

        $keywords = I('post.keywords', '', 'text');
        $map = array();
        $map['name'] = array('neq', '');
        if (!empty($keywords)) {
            $map['name'] = array('like', '%' . $keywords . '%');
        }
        $developer = D('AppstoreDeveloper')->where($map)->findPage(18);
        foreach ($developer['data'] as &$v) {
            $v['user'] = query_user(null, $v['uid']);
        }
        $this->assign('developers', $developer);
        $this->assign('current', 'developer');
        $this->display();
    }

    public function shops()
    {
        $map['status'] = 1;
        list($order, $param, $map) = $this->handleParamShops($map);
        $lists = D('AppstoreShop')->where($map)->order($order)->findPage(10);
        foreach ($lists['data'] as &$v) {
            $v['user'] = query_user(array('space_link', 'avatar128'), $v['uid']);
        }
        unset($v);

        //推荐start
        $can_manage=check_auth('Appstore/Admin/manage', -1);
        $recommend_shop_ids=modC('recommend_shop','','Appstore');
        if($recommend_shop_ids!=''){
            $order="find_in_set(uid,'".$recommend_shop_ids."')";
            $recommend_shop = D('AppstoreShop')->where(array('status' => 1,'uid' => array('in',explode(',',$recommend_shop_ids))))->order($order)->select();
        }else{
            $recommend_shop=null;
        }
        foreach($recommend_shop as &$val){
            $val['user'] = query_user(array('nickname'), $val['uid']);
        }
        unset($val);
        if($can_manage){
            if($recommend_shop_ids!=''){
                $shop = D('AppstoreShop')->where(array('uid' => array('status' => 1,'not in',explode(',',$recommend_shop_ids))))->select();
            }else{
                $shop = D('AppstoreShop')->where(array('status' => 1))->order('sales_count desc')->select();
            }
            foreach($shop as &$val){
                $val['id']=$val['uid'];
            }
            unset($val);
            $this->assign('goods', $shop);
        }
        $this->assign('recommond_goods', $recommend_shop);
        $this->assign('can_manage',$can_manage );
        //推荐end
        $this->assign('lists', $lists);
        $this->assign('current', 'shop');
        $this->setTitle('店铺——云市场');
        $this->display();
    }

    public function shop()
    {
        $aUid = I('get.id', 0, 'intval');
        $shop = D('AppstoreShop')->find($aUid);

        $shop['user'] = query_user(array('space_link', 'avatar128'), $shop['uid']);

        unset($v);

        $plugins = $data = D('AppstorePlugin')->getLimit(array('uid' => $aUid, 'status' => 1), 5, 'update_time desc', 1);
        $modules = $data = D('AppstoreModule')->getLimit(array('uid' => $aUid, 'status' => 1), 5, 'update_time desc', 1);
        $themes = $data = D('AppstoreTheme')->getLimit(array('uid' => $aUid, 'status' => 1), 6, 'update_time desc', 1);
        $this->assign('plugins', $plugins);
        $this->assign('modules', $modules);
        $this->assign('themes', $themes);
        $this->assign('shop', $shop);
        $this->assign('current', 'shop');
        $recommond_goods = D('AppstoreGoods')->where(array('id' => array('in', explode(',', $shop['recommond_goods']))))->select();
        $goods = D('AppstoreGoods')->where(array('uid' => $shop['uid'], 'status' => 1, 'id' => array('not in', explode(',', $shop['recommond_goods']))))->select();


        $this->assign('goods', $goods);
        $this->assign('recommond_goods', $recommond_goods);

        $this->assign('can_manage', check_auth('Appstore/Admin/manage', $shop['uid']));
        $this->display();
    }

    public function getGoods()
    {
        $aId = I('get.id', 0, 'intval');
        $goods = D('AppstoreGoods')->find($aId);
        $this->assign('goods', $goods);
        $this->display();
    }

    public function setShopRecommonedGoods()
    {
        $aId = I('post.id', 0, 'intval');
        $aUid = I('post.shop_id', 0, 'intval');
        $goods = D('AppstoreGoods')->find($aId);
        $shop = D('AppstoreShop')->find($aUid);
        if ($goods['uid'] != $shop['uid']) {
            //店铺和商品无法对应
            $this->error('设置失败，商品所属店铺不是当前店铺。');
        }
        if (check_auth('Appstore/Admin/manage', $shop['uid']) == false) {
            //无权设置
            $this->error('设置失败，当前用户并不能设置此店铺的推荐商品。');
        } else {
            $recommond_goods = explode(',', $shop['recommond_goods']);
            if ($recommond_goods[0] == '') {
                unset($recommond_goods[0]);
            }
            array_push($recommond_goods, $aId);
            //推进该商品，并排除重复
            $shop['recommond_goods'] = implode(',', array_unique($recommond_goods));
            $result = D('AppstoreShop')->save($shop);
            if ($result === false) {
                $this->error('设置失败，无法写入推荐商品信息。');
            } else {
                $this->success('设置成功。');
            }


        }
    }

    public function setRecommonedGoods()
    {
        $aId = I('post.id', 0, 'intval');
        $aEntity = I('post.entity', '1', 'text');
        $goods_entity=array(
            1=>'plugin',
            2=>'module',
            3=>'theme',
            4=>'service',
            5=>'shop'
        );
        if($aEntity==5){
            $shop=D('AppstoreShop')->where(array('uid'=>$aId,'status'=>1))->find();
            if(!$shop){
                //该店铺不存在或未启用
                $this->error("该店铺不存，不能被推荐。");
            }
        }else{
            $goods = D('AppstoreGoods')->find($aId);
            if ($goods['entity'] != $aEntity) {
                //商品类型与推荐类型（插件）无法对应
                $this->error("商品类型与推荐类型（{$goods_entity[$aEntity]}）不符。");
            }
        }
        if (check_auth('Appstore/Admin/manage', -1) == false) {
            //无权设置
            $this->error('设置失败，您不是小编，没有设置推荐权限。');
        } else {
            $recommend_ids=modC('recommend_'.$goods_entity[$aEntity],'','Appstore');
            $recommend_ids = explode(',', $recommend_ids);
            if ($recommend_ids[0] == '') {
                unset($recommend_ids[0]);
            }
            array_push($recommend_ids, $aId);
            //推进该商品，并排除重复
            $recommend_ids = implode(',', array_unique($recommend_ids));
            $conf_name='_APPSTORE_' . strtoupper('recommend_'.$goods_entity[$aEntity]);
            $config['name'] = $conf_name;
            $config['type'] = 0;
            $config['title'] = '';
            $config['group'] = 0;
            $config['extra'] = '';
            $config['remark'] = '';
            $config['create_time'] = time();
            $config['update_time'] = time();
            $config['status'] = 1;
            $config['value'] = $recommend_ids;
            $config['sort'] = 0;
            $res=D('Config')->add($config, null, true);
            if ($res) {
                S('conf' . $conf_name, $recommend_ids);
                $this->success('设置成功。');
            } else {
                $this->error('设置失败，无法写入推荐商品、店铺信息。');
            }
        }
    }

    /**
     * @param $keywords
     * @param $map
     * @return mixed
     * @auth 陈一枭
     */
    private function handleKeywords($keywords, $map)
    {
        if ($keywords != '') {
            $keywords = op_t(urldecode($keywords));
            $_GET['keywords'] = urlencode($keywords);
            $map['title'] = array('like', '%' . $keywords . '%');
            $this->assign('keywords', $keywords);
            return $map;
        }
        return $map;
    }

    /**
     * 下载文件
     */
    public function download()
    {
        $versionModel = D('AppstoreVersion');
        $aId = I('id', 0, 'intval');
        if ($aId != 0) {
            //普通点击下载按钮方式下载
            $version = $versionModel->find($aId);
            $this->requirePayed($version);
        } else {
            //通过安装程序下载
            $token = I('token', '', 'text');
            $version = $versionModel->getVersionByToken($token);
        }
        if ($version['id'] == 0 || $version['status'] != 1) {
            $this->error('版本不存在或已被删除。');
        } else {
            if (intval($version['pack']) == 0) {
                $this->error('文件不存在。');
            }
            $goods = D('AppstoreGoods')->find($version['goods_id']);
            D('AppstoreVersion')->where(array('id' => intval($version['id'])))->setInc('download_count');

            D('AppstoreResource')->where(array('id' => intval($version['goods_id'])))->setInc('total_download_count');
            $current_uid = get_uid() ? get_uid() : $version['uid'];

            if (is_tip($goods['uid'])) {
                if (get_uid()) {
                    D('Common/Message')->sendMessage($goods['uid'], text($goods['title']) . '被下载', '商品——' . text($goods['title']), 'appstore/admin/myplugin', array(), $current_uid, 2);
                } else {
                    D('Common/Message')->sendMessage($goods['uid'], text($goods['title']) . '被在线安装', '商品——' . text($goods['title']), 'appstore/admin/myplugin', array(), $current_uid, 2);
                }

            }
            if (!D('Appstore/AppstoreWatch')->checkWatched($version['goods_id'], $current_uid)) {
                D('Appstore/AppstoreWatch')->watch($version['goods_id'], 0, $current_uid);
                D('Common/Message')->sendMessageWithoutCheckSelf($current_uid, '云市场自动订阅通知', "系统已自动订阅您所购买的商品《{$goods['title']}》，如需取消订阅，请到商品详情页手动取消。", 'Appstore/Index/goodsDetail', array('id' => $version['goods_id']), $current_uid, 2);
            }

            $fileModel = D('File');
            if ($fileModel->download(C('DOWNLOAD_UPLOAD.rootPath'), intval($version['pack'])) == false) {
                $this->error($fileModel->getError());
            };
        }

    }

    /**
     * @param $data
     * @param $v
     * @return array
     */
    public function getVersions($data)
    {
        $versions = D('AppstoreVersion')->where(array('status' => 1, 'goods_id' => $data['id']))->order('create_time desc')->select();
        foreach ($versions as &$v) {
            $v['log'] = explode("\r\n", $v['log']);
            $v['log'] = '<ul><li>' . implode('</li><li>', $v['log']) . '</li></ul>';
        }

        unset($v);
        return $versions;
    }


    /**
     * 在线安装，服务器端部分
     */
    public function setup()
    {
        $aId = I('get.id', '-1', 'intval');

        if (!is_login()) {
            $this->error('请登录后访问。');
        }
        //检测是否已经绑定了网站
        $isBinded = D('Appstore/AppstoreWebsite')->isBinded(get_uid());

        $versionModel = D('AppstoreVersion');
        $version = $versionModel->where(array('id' => $aId))->find();
        $version['log'] = $versionModel->formatLog($version['log']);
        if (floatval($version['need_buy']) != 0) {
            //付费的扩展必须先绑定网站方可下载
            if (!$isBinded) {
                $this->error('付费的扩展必须绑定网站域名后才可下载。<a href="' . U('admin/bind') . '">立即绑定</a>。', U('Admin/bind'));
            }
            $isPayed = D('AppstoreOrder')->isPayed($version['id'], get_uid());
            if ($isPayed) {
                $this->assign('token', $versionModel->getToken($aId, get_uid()));
            }
            $this->assign('payed', $isPayed);
        } else {
            $this->assign('token', $versionModel->getToken($aId, get_uid()));
        }
        $goods = D('AppstoreGoods')->getById($version['goods_id']);
        $data['version'] = $version;
        $data['goods'] = $goods;

        $this->assign($data);
        $this->display();


    }

    /**
     * 通过信息生成安装指纹，用于主程序验证。
     */
    public function getSetupToken()
    {
        $aId = I('post.version_id', -1, 'intval');

        $versionModel = D('AppstoreVersion');
        $result = $versionModel->getToken($aId, get_uid());
        if ($result === false) {
            $this->error($versionModel->getError());
        } else {
            $this->success($result['token']);
        }

    }

    /**
     * @param $version
     */
    public function requirePayed($version)
    {
        if ($version['need_buy']) {
            $isPayed = D('AppstoreOrder')->isPayed($version['id'], get_uid());
            if (!$isPayed) {
                $this->error('请购买之后再下载。即将跳转到购买页面。', U('Index/buy', array('id' => $version['id'])));
            }
        }

        $this->assign('payed', 1);
    }


    public function order()
    {
        if (IS_POST) {
            $aOrderId = I('post.order_id', 0);
            $order = D('AppstoreOrder')->getById($aOrderId);
            if ($order['uid'] != get_uid()) {
                $this->error('不能支付不是自己的订单');
            }
            if ($order['status'] != 1) {
                $this->error('该订单状态不允许支付');
            }
            if ($order['pay_ok'] == 1) {
                $this->error('该订单已被支付');
            }

            $res = D('AppstoreOrder')->payOk($aOrderId);
            if ($res) {

                $this->success('支付成功', U('appstore/index/goodsdetail', array('id' => $order['goods_id'])));
            } else {
                $this->error(D('AppstoreOrder')->getError());
            }

        } else {
            $aOrderId = I('get.id', 0);
            $order = D('AppstoreOrder')->getById($aOrderId);
            if (empty($order)) {
                $this->error('该订单不存在！');
            }
            $order['version'] = $version = D('AppstoreVersion')->getVersion($order['version_id']);
            $order['goods'] = D('AppstoreGoods')->getById($version['goods_id']);
            $order['score'] = $score = D('Ucenter/Score')->getType(array('id' => $order['score']));
            $this->assign('order', $order);
            $this->display();
        }

    }

    public function cancelOrder()
    {
        $aOrderId = I('post.id', 0);
        $order = D('AppstoreOrder')->getById($aOrderId);
        //判断权限
        $this->checkAuth('Appstore/Admin/manage', $order['uid']);

        if ($order['status'] != 1) {
            $this->error('该订单状态无法被操作');
        }
        if ($order['pay_ok'] == 1) {
            $this->error('该订单已被支付');
        }

        $res = D('AppstoreOrder')->cancelOrder($aOrderId);
        if ($res) {
            $this->success('取消成功', 'refresh');
        } else {
            $this->error('取消失败');
        }

    }

    /**
     * @param $param
     * @param $map
     * @return array
     */
    protected function handleParam($param, $map)
    {
        $order = array();
        if ($param['type'] == 'free') {
            $map[''];
        }
        switch ($param['order']) {
            case 'create':
                $order['create_time'] = 'desc';
                break;
            case 'update':
                $order['update_time'] = 'desc';
                break;
            case 'sales':
                $order['sales'] = 'desc';
                break;
            case 'watch':
                $order['watch_count'] = 'desc';
                break;
            default:
                $param['order'] = 'update';
                $order['update_time'] = 'desc';
        }
        switch ($param['type']) {
            case 'notfree':
                $map['need_buy'] = 1;
                break;
            case 'free':
                $map['need_buy'] = 0;
                break;
            default:
                $param['type'] = 'all';

        }
        $this->assign('param', $param);
        return array($order, $param, $map);
    }

    protected function handleParamShops($map)
    {
        $order = array();
        $param = I('get.', 'text');
        $keywords = I('post.keywords', '', 'text');
        if ($param['type'] == 'free') {
            $map[''];
        }
        switch ($param['order']) {
            case 'create':
                $order['create_time'] = 'desc';
                break;
            case 'sales_count':
                $order['sales_count'] = 'desc';
                break;
            case 'goods_count':
                $order['goods_count'] = 'desc';
                break;
            case 'star':
                $order['star'] = 'desc';
                break;
            default:
                $order['sales_count'] = 'desc';
        }
        if ($keywords) {
            $map['title'] = array('like', '%' . $keywords . '%');
            $param['keywords'] = $keywords;
        } else {
            if ($param['keywords']) {
                $map['title'] = array('like', '%' . urldecode($param['keywords']) . '%');
            }
        }
        if ($param['filter_gold'] == 1) {
            $map['gold'] = 1;
        }
        if ($param['filter_official'] == 1) {
            $map['official'] = 1;
        }
        $param['keywords'] = urlencode(urldecode($param['keywords']));
        $this->assign('gold', !$param['filter_gold']);
        $this->assign('official', !$param['filter_official']);
        $this->assign('');
        $this->assign('param', $param);
        return array($order, $param, $map);
    }
}